import 'package:photo_frame/net/model/asset_trans_model.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart' as p;

class DatabaseManager {
  static final DatabaseManager instance = DatabaseManager._init();
  static Database? _database;

  DatabaseManager._init();

  Future<Database> get database async {
    if (_database != null) return _database!;
    _database = await _initDB('asset_trans.db');
    return _database!;
  }

  Future<Database> _initDB(String filePath) async {
    final dbPath = await getDatabasesPath();
    final path = p.join(dbPath, filePath);
    print(path);
    return await openDatabase(path, version: 1, onCreate: _createDB);
  }

  Future _createDB(Database db, int version) async {
    await db.execute('''
    CREATE TABLE IF NOT EXISTS asset_trans(
      id INTEGER PRIMARY KEY,
      assetId TEXT,
      toFrameId TEXT,
      toFrameName TEXT,
      toFrameFolderName TEXT,
      markDesc TEXT,
      transDate TEXT,
      batchId TEXT,
      transStatus INTEGER
    )
    ''');
  }

  Future<AssetTransModel> create(AssetTransModel model) async {
    final db = await instance.database;
    await db.insert('asset_trans', model.toMap());
    return model;
  }

  Future<List<AssetTransModel>> readAll() async {
    final db = await instance.database;
    final result = await db.query('asset_trans');
    return result.map((json) => AssetTransModel.fromMap(json)).toList();
  }

  Future<int> update(AssetTransModel model) async {
    final db = await instance.database;
    return db.update(
      'asset_trans',
      model.toMap(),
      where: 'id = ?',
      whereArgs: [model.id],
    );
  }

  Future<int> delete(int id) async {
    final db = await instance.database;
    return await db.delete(
      'asset_trans',
      where: 'id = ?',
      whereArgs: [id],
    );
  }

  Future<int> batchDelete(String batchId) async {
    final db = await instance.database;
    return await db.delete(
      'asset_trans',
      where: 'batchId = ?',
      whereArgs: [batchId],
    );
  }

  Future<int> deleteAll() async {
    final db = await instance.database;
    return await db.delete('asset_trans');
  }

  Future close() async {
    final db = await instance.database;
    db.close();
  }
}
